define(function(require, exports, module) {
  "use strict";
  var Base = require("smartartBase");

  module.exports = Base.SmartartBaseView.extend({
    initialize: function(config, options) {

      var isFirstCreate = !config.itemId;

      Base.SmartartBaseView.prototype.initialize.apply(this, arguments);
      // set this flag  to notify the removeChild not to trigger the event.
      this.model.set("_checkNumber", true);

      if (isFirstCreate) {
        this._firstInit();
      }
      this._checkNumber();

      this.fitSize();
    },
    _firstInit: function() {
      // get the initialize data from this.model.
      this._createItem();
      this._createItem();
    },
    _createItem: function() {
      var manuscriteWidget = this.create("item", {
        type: "newManuscript"
      });
      var data = this.getSelfData();
      manuscriteWidget.dataChange({
        name: "view",
        value: data.view
      }, manuscriteWidget.itemId, true);
      manuscriteWidget.dataChange({
        name: "inputWidth",
        value: parseInt(data.inputWidth)
      }, manuscriteWidget.itemId, true);
      if (data.view == "Pozidriv") {
        manuscriteWidget.dataChange({
          name: "inputHeight",
          value: parseInt(data.inputWidth)
        }, manuscriteWidget.itemId, true);
      } else {
        manuscriteWidget.dataChange({
          name: "inputHeight",
          value: parseInt(data.inputHeight)
        }, manuscriteWidget.itemId, true);
      }
      var manuscrites = this._getAllManuscrites();
      this.addChild(manuscriteWidget);

      var lastItem;
      var position;
      if (manuscrites.length) {
        manuscrites.reverse();
        lastItem = manuscrites[0];
        position = lastItem.model.get("position");
        manuscriteWidget.model.setPositionDiff({
          left: (position.left || 0) + parseInt(this.getSelfData().inputWidth),
          top: (position.top || 0)
        });
      }
      this.fitSize();
      manuscriteWidget.model.set("hasSignalSlot", false);
      return manuscriteWidget;
    },
    _getAllManuscrites: function() {
      return this.children.filter(function(child) {
        return child.model.get("type") === "newManuscript";
      });

    },
    setData: function(type, value) {
      var data = this.getSelfData();
      data[type] = value;
      this.setSelfData(_.cloneDeep(data));
    },
    getData: function(type) {
      var data = this.getSelfData();
      return data[type];
    },
    refreshUI: function(data) {
      var changedData = this._createDataChange(data);


      // doesn't change anything
      if (!changedData.items || // item value doesn't exists
        changedData.items.value === changedData.items.oldValue || // it equals the oldValue
        changedData.items.value === this.children.length // it equals the existed card
      ) {} else {
        var itemsData = changedData.items;
        var diff = itemsData.value - itemsData.oldValue;
        if (diff > 0) {
          this._addChildrenByDiff(diff);
        } else {
          this._removeChildrenByDiff(-diff);
        }
      }
      //view
      if (!changedData.view || // item value doesn't exists
        changedData.view.value === changedData.view.oldValue // it equals the oldValue
      ) {} else {
        var viewData = changedData.view;
        this._getAllManuscrites().forEach(function(item) {
          item.dataChange({
            name: "view",
            value: viewData.value
          }, item.itemId, true);
        });
        this.fitSize();
      }
      //inputHeight
      if (!changedData.inputHeight || // item value doesn't exists
        changedData.inputHeight.value === changedData.inputHeight.oldValue // it equals the oldValue
      ) {} else {
        var inputHeightData = changedData.inputHeight;
        this._getAllManuscrites().forEach(function(item) {
          item.dataChange({
            name: "inputHeight",
            value: inputHeightData.value
          }, item.itemId, true);
        });
        this.fitSize();
      }
      //inputWidth
      if (!changedData.inputWidth || // item value doesn't exists
        changedData.inputWidth.value === changedData.inputWidth.oldValue // it equals the oldValue
      ) {} else {
        var inputWidthData = changedData.inputWidth;
        var _this = this;
        this._getAllManuscrites().forEach(function(item, index) {
          item.dataChange({
            name: "inputWidth",
            value: inputWidthData.value
          }, item.itemId, true);
          if (index > 0) {
            var offset = inputWidthData.value - inputWidthData.oldValue;
            item.model.setPositionDiff({
              left: offset + (index - 1) * (offset > 0 ? 1 : -1),
              top: 0
            });
          }
        });
        this.fitSize();
      }

      Base.SmartartBaseView.prototype.refreshUI.apply(this, [data]);
    },
    /**
     * remove children by diff, it removes from back to front.
     * @param diff
     * @private
     */
    _removeChildrenByDiff: function(diff) {
      var manuscrites = this.children.filter(function(item) {
        return item.model.get("type") === "newManuscript";
      });
      manuscrites = manuscrites.reverse();
      manuscrites.some(function(item, i) {
        item.remove();
        if (i + 1 === diff) {
          return true;
        }
      });
      this._checkNumber();
    },
    /**
     * Add child by diff number
     * @param diff
     * @private
     */
    _addChildrenByDiff: function(diff) {
      for (var i = 0; i < diff; i++) {
        this._createItem();
      }
      this._checkNumber();
    },
    /**
     * Check the number of manuscrites after user operating.
     * @private
     */
    _checkNumber: function() {
      var manuscrites = this.children.filter(function(item) {
        return item.model.get("type") === "newManuscript";
      });
      var hasDelete = true;
      if (manuscrites.length < 3) {
        hasDelete = false;
      }
      var existedItemId = [];
      manuscrites.forEach(function(item) {
        existedItemId.push(item.itemId);
        item.model.set("hasDelete", hasDelete);
      });

      // remove data from saresult
      this.setData("items", manuscrites.length);

    },
    /**
     * Create data change object from data
     * @param data
     * @returns {Object}
     * @private
     */
    _createDataChange: function(data) {
      var oldData = this.getSelfData();
 
      var changedData = {};
      data.forEach(function(item) {
        var name = item.name;
        var value = item.value;
        var oldValue = oldData[name];
        changedData[name] = {
          value: value,
          oldValue: oldValue
        };
      }.bind(this));
      return changedData;
    },
    /**
     * When remove child, Need to check the children's length
     *  to keep the children number is bigger than 1
     * @param view
     */
    removeChild: function(view) {
      // remove view
      Base.SmartartBaseView.prototype.removeChild.apply(this, [view]);


      if (this.model.get("_checkNumber")) {
        this._checkNumber();
        this.trigger("data.changed", this.model);
      }

    },
    remove: function() {
      this.model.set("_checkNumber", false);
      Base.SmartartBaseView.prototype.remove.apply(this, arguments);
    }
  });

});